<?php

class Asterisk
{
    private $sock = null;
    
    
	function __construct()
	{
	}
 
	public function connect($ip, $port, $username, $password)
	{
        if(is_null($this->sock) === false) $this->disconnect;
        
        $this->sock = fsockopen($ip, $port);
        
        $buf = "";
        $buf .= "Action: login\r\n";
        $buf .= "Username: $username\r\n";
        $buf .= "Secret: $password\r\n";
        $buf .= "\r\n";
        
        fputs($this->sock, $buf);
        $ans = fread($this->sock, 1000000);
    }
    
    public function disconnect()
    {
        $buf = "Action: logoff\r\n\r\n";
        fputs($this->sock, $buf);
        $ans = fread($this->sock, 1000000);
        fclose($this->sock);
    }
 
	public function sendSMS($phone, $message)
	{
        $msg = str_replace("\n", "", str_replace("\r", "", $msg));
        $buf = "";
        $buf .= "Action: DatacardSendSMS\r\n";
        $buf .= "Device: datacard0\r\n";
        $buf .= "Number: $phone\r\n";
        $buf .= "Message: $msg\r\n";
        $buf .= "\r\n";
        
        fputs($this->sock, $buf);
        $ans = fread($this->sock, 1000000);
	}
}